﻿using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;

/// <summary>
/// URLRewriter 的摘要说明
/// </summary>
public class URLRewriter : System.Web.UI.Page, IHttpModule //IHttpModule //实现“IHttpModule”接口 IHttpHandler,
{
    public URLRewriter()
    {
    }

    public void Init(HttpApplication context)
    {
        context.BeginRequest += new EventHandler(this.ReUrl_BeginRequest);
        context.EndRequest += new EventHandler(this.ReUrl_EndRequest);
    }

    public void Dispose()
    {
    }

    protected string _url = "";
    protected string strUrl
    {
        get { return _url; }
    }


    private void ReUrl_BeginRequest(object sender, EventArgs e)
    {
        HttpContext Context = ((HttpApplication)sender).Context;
        Context.Response.Buffer = true;
        Context.Response.ExpiresAbsolute = DateTime.Now.AddSeconds(-1.0);
        Context.Response.Expires = 0;
        Context.Response.CacheControl = "no-cache";

        //取得原始URL屏蔽掉参数
        _url = Context.Request.RawUrl.ToString().ToLower();
        //_url = Context.Request.Url.ToString().ToLower();
        string _postfix = ".aspx";
        string _querystring = "";
        string pathinfo = string.Empty;
        string _path = "";
        try
        {
            //分解伪静态信息
            if (_url.Contains("-"))
            {
                int intpathIndex = _url.IndexOf('-');
                _path = _url.Substring(0, intpathIndex);
            }
            else if (_url.Contains("."))
            {
                _path = _url.Substring(0, _url.IndexOf('.'));
            }
            string str = _path;
            if (_url.Contains("."))
            {
                if (_url.IndexOf('.') - _path.Length > 0)
                {
                    str = _url.Substring(_path.Length, _url.IndexOf('.') - _path.Length);
                }
            }
            if (str.Contains("-p"))
            {
                str = str.Replace("-p", "&page=");
            }
            if (str.Contains("-"))
            {
                str = str.Replace("-", "id=");
            }
            _querystring = str;
            if (_url.Contains("?"))
            {
                if (!_querystring.Equals(_path))
                    _querystring += "&" + _url.Substring(_url.IndexOf("?") + 1);
                else
                    _querystring = _url.Substring(_url.IndexOf("?") + 1);
            }
        }
        catch
        {
            Context.RewritePath("/Error.aspx");
        }
        if (_url.EndsWith("/admin"))   //网站后台处理
        {
            Context.RewritePath("/admin/index.aspx");
            return;
        }
        if (_url == "/")              //网站首页
        {
            Context.RewritePath("/default.aspx");
        }
        if (_url.StartsWith("/shop"))
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            CreateShop(Context);
        }

        if (_url.StartsWith("/supply") || _url.StartsWith("/purchase") || _url.StartsWith("/expo"))    //供求信息
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))     //处理简写问题
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
                //Context.RewritePath(_path + _postfix);
            }
            else
            {
                string strbs = "";
                if (_url.EndsWith("/supply") || _url.EndsWith("/purchase"))
                {
                    strbs = "/";
                }
                Context.RewritePath(_url + strbs + "trade.aspx");
            }
        }

        if (_url.StartsWith("/help"))    //供求信息
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/help"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "trade.aspx");
            }
        }

        if (_url.StartsWith("/webnews"))    //供求信息
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/webnews"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "trade.aspx");
            }
        }

        if (_url.StartsWith("/news"))    //资讯信息
        {

            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/news"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "index.aspx");
            }
        }
        if (_url.StartsWith("/job"))    //求职招聘信息
        {

            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                if (_path.Contains("jobtrade"))
                {
                    _path = _path.Replace("jobtrade", "Job");
                    _querystring += "&mode=Job_Trade";
                }
                else if (_path.Contains("resumetrade"))
                {
                    _path = _path.Replace("resumetrade", "Job");
                    _querystring += "&mode=Job_Categories";
                }
                else if (_path.Contains("jobdetail"))
                {
                    _path = _path.Replace("jobdetail", "Job");
                    _querystring += "&mode=Job_Detail";
                }
                else if (_path.Contains("resumedetail"))
                {
                    _path = _path.Replace("resumedetail", "Job");
                    _querystring += "&mode=Job_Wanted";
                }
                else if (_path.Contains("index"))
                {
                    //_querystring = _url.Substring(_url.LastIndexOf('?'));
                    //_querystring = Context.Request.QueryString["jobid"]; ;

                }
                else
                {
                    _querystring = "mode=Job_Index";
                }
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/job"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "job.aspx", pathinfo, "mode=JOB_LAVOROINDEX");
            }
        }

        if (_url.StartsWith("/know"))    //资讯信息
        {

            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/know"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "index.aspx");
            }
        }


        if (_url.StartsWith("/agent"))    //招商加盟
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/agent"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "index.aspx");
            }
        }

        if (_url.EndsWith("/member") || _url.EndsWith("/member/"))    //资讯信息
        {

            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }
            Context.RewritePath("/Member/index.aspx");
        }

        if (_url.StartsWith("/company"))   //公司信息
        {
            if (!Base.BasePage.Config.isClosed)
            {
                Context.RewritePath("~/default.aspx");
                return;
            }

            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/company"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "trade.aspx");
            }
        }

        if (_url.StartsWith("/product"))   //公司信息
        {
            if (_url.Contains("."))
            {
                Context.RewritePath(_path + _postfix, pathinfo, _querystring);
            }
            else
            {
                string strnews = "";
                if (_url.EndsWith("/product"))
                {
                    strnews = "/";
                }
                Context.RewritePath(_url + strnews + "trade.aspx");
            }
        }


        if (_url.StartsWith("/search"))   //公司信息
        {
            Context.RewritePath(_path + _postfix);
        }

    }

    /// <summary>
    /// 生成商铺
    /// </summary>
    /// <param name="Context"></param>
    private void CreateShop(HttpContext Context)
    {
        Regex[] Reg = new Regex[8];
        RegexOptions options;
        options = RegexOptions.Singleline | RegexOptions.IgnoreCase;
        Reg[0] = new Regex(@"index/\w+", options);
        Reg[1] = new Regex(@"newslist/\w+", options);
        Reg[2] = new Regex(@"supply/\w+", options);
        Reg[3] = new Regex(@"contact/\w+", options);
        Reg[4] = new Regex(@"certify/\w+", options);
        Reg[5] = new Regex(@"profile/\w+", options);
        Reg[6] = new Regex(@"newsinfo/\w+", options);
        Reg[7] = new Regex(@"Job/\w+", options);
        //Reg[2] = new Regex(@"{PR_\w+}", options);
        int tp = -1;
        for (int i = 0; i < Reg.Length; i++)
        {
            Match m = Reg[i].Match(strUrl);
            if (m.Success)//匹配成功
            {
                tp = i;
                break;
            }
        }
        try
        {

            string LoginName = strUrl.Substring(strUrl.LastIndexOf('/') + 1, strUrl.IndexOf('.') - strUrl.LastIndexOf('/') - 1);
            string strType = "";
            //if (tp == 2)
            //{
            if (strUrl.IndexOf('?') > 0)
                strType = strUrl.Substring(strUrl.LastIndexOf('?') + 1); //取得会员产品类别ID
            //}
            switch (tp)
            {
                case 0:
                    // Server.Transfer(@"/Shops/Index.aspx?LoginName=" + LoginName);//重写路径
                    Context.RewritePath("~/Shops/Index.aspx?LoginName=" + LoginName);
                    break;
                case 1:
                    Context.RewritePath(@"~/Shops/Newslist.aspx?LoginName=" + LoginName);//重写路径
                    break;
                case 2:
                    if (strType != "") LoginName += "&" + strType;
                    Context.RewritePath(@"~/Shops/Supply.aspx?LoginName=" + LoginName);
                    break;
                case 3:
                    Context.RewritePath(@"~/Shops/Contact.aspx?LoginName=" + LoginName);//重写路径
                    break;
                case 4:
                    Context.RewritePath(@"~/Shops/Certify.aspx?LoginName=" + LoginName);//重写路径
                    break;
                case 5:
                    Context.RewritePath(@"~/Shops/Profile.aspx?LoginName=" + LoginName);//重写路径
                    break;
                case 6:
                    if (strType != "") LoginName += "&" + strType;
                    Context.RewritePath(@"~/Shops/NewsInfo.aspx?LoginName=" + LoginName);//重写路径
                    break;
                case 7:
                    Context.RewritePath(@"~/Shops/Job.aspx?LoginName=" + LoginName);//重写路径
                    break;
                default:
                    // Context.Response.Redirect(Url);
                    break;

            }
        }
        catch (Exception ex)
        {
            Context.RewritePath("~/Error.aspx");//重写路径
        }
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="args"></param>
    private void ReUrl_EndRequest(object sender, EventArgs args)
    {

    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="Context"></param>
    public void ProcessRequest(HttpContext Context)
    {
    }
    /// <summary>
    /// 实现“IHttpHandler”接口所必须的成员
    /// </summary>
    /// <value></value>
    public bool IsReusable
    {
        get { return false; }
    }
}
//}

